import WujieVue from 'wujie-vue3';
// import { setupApp, preloadApp} from "wujie";

import { acceptHMRUpdate, defineStore } from 'pinia';
import { getToken } from '@/utils/common-util';
import { useUserStore } from '@/store/user';
import { plugins } from '@/utils/micro-plugins';
const SET_APP_STORAGE = 'SET_APP_STORAGE';
// eslint-disable-next-line camelcase
const SET_MICRO_MENU = 'SET_MICRO_MENU';
const GENERATE_MICRO_MENU = 'GENERATE_MICRO_MENU';
const PRELOAD_MICRO = 'PRELOAD_MICRO';
const SET_MICRO_APP = 'SET_MICRO_APP';
const GET_MICRO_APP_PERMISSIONS = 'GET_MICRO_APP_PERMISSIONS';
const { setupApp, preloadApp } = WujieVue;

export interface wujieStore {
  microApp: any;
  microPermissions: any;
  appStorage: object;
}
/** 主应用模式使用该文件
 *  用于缓存子应用的菜单信息 和 子应用加载信息
 * */
export const useMicroStore = defineStore('micro', {
  state: (): wujieStore => ({
    microApp: [],
    microPermissions: {}, // 所有子应用菜单信息
    appStorage: {} // 子应用页签加载信息
  }),
  actions: {
    [SET_APP_STORAGE](appStorage: Array<string>) {
      this.appStorage = appStorage;
    },
    // 保存子应用的菜单信息
    [SET_MICRO_MENU](permissions) {
      this.microPermissions = permissions;
    },
    // 从菜单中遍历出所关联的子应用信息并缓存
    [SET_MICRO_APP](menu) {
      // 子应用的加载地址和子应用名称的对应关系存入 microApp 中，做预加载使用
      let url = menu.meta.microAppUrl;
      if (url && url.endsWith('/')) {
        url = url.slice(0, url.length - 1);
      }
      const microAppName = menu.meta.microAppCode;
      if (this.microApp[microAppName] === null || typeof this.microApp[microAppName] === 'undefined') {
        this.microApp[microAppName] = {
          url: menu.meta.microAppUrl,
          preloadFlag: menu.meta.preloadFlag
        };
      }
    },
    // 初始化子应用token，用户和 权限信息,并构建前端路由
    [GENERATE_MICRO_MENU](userPermissions) {
      // 按照子应用code 给递归前台菜单分类
      const menuMap = {};
      const classifyMicroAppByCode = (menuReocords) => {
        for (const menu of menuReocords) {
          if (menu.meta.siteType === '1') {
            // 微应用的菜单
            if (!menuMap[menu.meta.microAppCode]) {
              menuMap[menu.meta.microAppCode] = {};
            }
            menuMap[menu.meta.microAppCode][menu.id] = menu;
          }
          if (menu.children && menu.children.length > 0) {
            classifyMicroAppByCode(menu.children);
          }
        }
      };
      classifyMicroAppByCode(userPermissions.menuList);
      // 根据子应用code 将菜单，按钮权限，和列权限组合
      const appsMap = {};
      Object.keys(menuMap).forEach((key) => {
        appsMap[key] = {
          menuList: Object.values(menuMap[key]) || [],
          permissionButtonList: userPermissions.permissionButtonList,
          denyPermissionColumnList: userPermissions.denyPermissionColumnList,
          roleCodeList: userPermissions.roleCodeList
        };
      });
      this.microPermissions = appsMap;
    },
    // 预加载和预执行子应用信息
    async [PRELOAD_MICRO]() {
      if (!window.__POWERED_BY_WUJIE__) {
        // eslint-disable-next-line prefer-destructuring
        const microApp = this.microApp;
        const lifecycles = {
          beforeLoad: (appWindow) => console.log(`${appWindow.__WUJIE.id} beforeLoad 生命周期`),
          beforeMount: (appWindow) => console.log(`${appWindow.__WUJIE.id} beforeMount 生命周期`),
          afterMount: (appWindow) => console.log(`${appWindow.__WUJIE.id} afterMount 生命周期`),
          beforeUnmount: (appWindow) => console.log(`${appWindow.__WUJIE.id} beforeUnmount 生命周期`),
          afterUnmount: (appWindow) => console.log(`${appWindow.__WUJIE.id} afterUnmount 生命周期`),
          activated: (appWindow) => console.log(`${appWindow.__WUJIE.id} activated 生命周期`),
          deactivated: (appWindow) => console.log(`${appWindow.__WUJIE.id} deactivated 生命周期`),
          loadError: (url, e) => console.log(`${url} 加载失败`, e)
        };
        for (const microAppCode in microApp) {
          const item = microApp[microAppCode];
          const permissions = this.GET_MICRO_APP_PERMISSIONS(microAppCode);
          setupApp({
            name: microAppCode,
            url: item.url,
            props: { appName: microAppCode, permissions },
            fiber: true,
            exec: true,
            plugins,
            ...lifecycles
          });
          if (item.preloadFlag === '1') {
            // 预加载
            preloadApp({
              name: microAppCode
            });
          } else if (item.preloadFlag === '2') {
            // 预执行
            preloadApp({
              exec: true,
              name: microAppCode
            });
          }
          // startApp({
          //   name: microAppCode,
          //   url: item.url,
          //   el: ''
          // });
        }
      }
    },
    // 获取包含token , 用户信息，菜单，和按钮权限的所有子应用需要的权限信息
    [GET_MICRO_APP_PERMISSIONS](microAppCode: string) {
      const userStore = useUserStore();
      const token = getToken() || '';
      const userInfo = userStore.userInfo || {};
      return { token, userInfo, permissions: this.microPermissions[microAppCode] };
    }
  }
});

const hot = import.meta.webpackHot || (import.meta as any).hot;
if (hot) {
  hot.accept(acceptHMRUpdate(useMicroStore, hot));
}
